class RecommendItem < ActiveRecord::Base
	belongs_to :item
	named_scope :period, lambda {|*args| {:order => 'position asc',  :conditions => ['flag = ?', args.first]}}
	named_scope :filter, lambda {|*args| {:order => 'position asc', :conditions => ['recommend_type = ?', args.first]}}
	
	def self.saved(ids, flag, recommend_type, hot_keywords)
		RecommendItem.delete_all(["flag = ? and recommend_type = ?", flag, recommend_type])
		unless ids.nil?
			ids.each_with_index do |rid, i|
				next if rid.to_s.blank?
				remd = RecommendItem.new(:flag => flag,
																		:recommend_type => recommend_type,
																		:related_id => rid,
																		:position => i)
				remd.save
			end
		end
  	
  	unless hot_keywords.nil?
			hot_keywords.each_with_index do | keyword, i|
				next if keyword.nil? || keyword.blank?
				remd = RecommendItem.new(:flag => flag,
																		:recommend_type => recommend_type,
																		:hot_keyword => keyword,
																		:position => i)
				remd.save
			end
		end
	end
	
	def self.top_sale_products(cat1_id)
  end
  
  def self.filter_item(flag, type) 
  	Item.find_by_sql("select items.id, items.title, items.pic_url, items.price, items.cat1_id from items left join recommend_items on items.id = recommend_items.related_id where recommend_items.flag = #{flag} and recommend_type = #{type} order by position")
  end
  
  def self.valid_related_ids(ids, recommend_type)
  	ids.each do |id|
  		next if id.to_s.blank?
  		if(recommend_type == 0)
  			return "ok"
  		else
				return id unless Item.find_by_id(id)
			end
  	end
  	return "ok"
  end
end
